<?php
/**
 * 后台管理员管理控制器
 *
 * @author
 * @version
 */
class AdminAction extends AbstractAction
{
    /**
     * @var AdminModel
     */
	protected $Admin = NULL;
	/**
	 * @var Db
	 */
	protected $Db = NULL;
    /**
     * @var int
     */
	protected $_pagesize = 15;
    /**
     * @var string
     */
	protected $_dbprefix;

    /**
     * 控制器预初始化
	 *
	 * @return NULL
     */
	protected function _initialize()
    {
		parent::_initialize();
		$this->Admin = D('Admin/Admin');
		$this->Db = Db::getInstance();
		$this->_dbprefix = C('DB_PREFIX');
	}

    /**
     * 管理员管理首页
	 *
	 * @return HTML
     */
	public function index()
	{
		$this->display();
	}

    /**
     * 管理员分页查询
	 *
	 * @return JSON
     */
	public function page()
	{
		$where = array();
		$page = max((isset($_GET['page']) ? intval($_GET['page']) : 1), 1);
		$pagesize = max((isset($_GET['pagesize']) ? intval($_GET['pagesize']) : $this->_pagesize), 1);
        if (isset($_GET['keywords']) && $_GET['keywords']) {
           	$where['username'] = array('like', '%'.$_GET['keywords'].'%');
           	$where['name'] = array('like', '%'.$_GET['keywords'].'%');
			$where['_logic'] = 'OR';
        }
		$orderby = '`userid` DESC';
		if (isset($_GET['orderby']) && $_GET['orderby']) {
			$order = explode('|', $_GET['orderby']);
			$orderby = "$order[0] $order[1]";
		}
		$result = $this->Admin->where($where)
			->order($orderby)
			->limit($pagesize)->page($page)
			->select();
		$total = $this->Admin->where($where)->count();
		echo json_encode(array('data'=>$result, 'total'=>$total));
	}

    /**
     * 添加管理员
	 *
	 * @return HTML & JSON
     */
	public function add()
	{
        if ($this->isPost()) {
            $result = false;
            // 验证创建对象
            if ($data = $this->Admin->create()) {
                // 新增
                if ($userid = $this->Admin->add($data)) {
                    $result = true;
                    $row = $this->Admin->find($userid);
                }
            }
            echo json_encode(array('state'=>$result, 'data'=>$row, 'error'=>$this->Admin->getError()));
        } else {
            $this->display();
        }
	}

    /**
     * 编辑管理员
	 *
	 * @return HTML & JSON
     */
	public function edit()
	{
		$userid = intval($_REQUEST['userid']);
		if (!$userid) {
			$this->_error('无效编辑账户');
		}

		if ($this->isPost()) {
			$result = false;
			if ($data = $this->Admin->create()) {
				if ($this->Admin->edit($userid, $data) !== false) {
					$result = true;
					$row = $this->Admin->find($userid);
				}
			}
			echo json_encode(array('state'=>$result, 'data'=>$row, 'error'=>$this->Admin->getError()));

		} else {
			import('@.Helper.Form');
            $data = $this->Admin->find($userid);
			$sex_radio = Form::radio(array(
				'value' => $data['sex'],
				'name' => 'sex',
				'options' => array(1=>'男',2=>'女')
			));
			$state_radio = Form::radio(array(
				'value' => $data['disabled'],
				'name' => 'disabled',
				'options' => array(0=>'启用',1=>'禁用')
			));

			$this->assign($data);
			$this->assign('sex_radio', $sex_radio);
			$this->assign('state_radio', $state_radio);
			$this->display();
		}
	}

	/**
	 * 删除管理员
	 *
	 * @return JSON
	 */
	function delete()
	{
		$result = array('state'=>false, 'error'=>false);
		if (!isset($_POST['id'])) {
			$result['error'] = '无对象可删除';
			exit(json_encode($result));
		}
		$ids = array_unique(array_filter(array_map('trim', explode(',', $_POST['id']))));

		foreach($ids as $userid) {
			$return = $this->Admin->where('userid='.$userid)->delete();
		}
		$result = !$return ? array('state'=>false,'error'=>$this->Admin->getError()) : array('state'=>true);
		exit(json_encode($result));
	}


    /**
	 * 私有方法，提供公共错误输出接口
	 *
     * @param $msg
	 * @return NULL
     */
	private function _error($msg)
	{
		if ($this->isPost()) {
			exit(json_encode(array('state'=>false,'error'=>$msg)));
		} else {
			exit ($msg);
		}
	}
}